package com.example.d10_homework.homework01;

import java.io.*;
import java.net.Socket;

public class ClientHandler implements Runnable {
    private static final String SENSITIVE_WORD = "操";
    private static final String REPLACEMENT = "**";

    private final Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter fileWriter = new BufferedWriter(new FileWriter("received_file.txt"))
        ) {
            out.println("欢迎光临！请上传文件(文本文件)！");

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.equals("END")) break; // 客户端发送"END"表示文件传输结束
                String sanitizedLine = inputLine.replace(SENSITIVE_WORD, REPLACEMENT);
                fileWriter.write(sanitizedLine + System.lineSeparator());
                fileWriter.flush();
            }

            out.println("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}